<template>
	<section>
		<!--高級查詢工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item><!-- keyword高級查詢关键字-->
					<el-input v-model="filters.keyword" placeholder="部门查询"></el-input>
				</el-form-item>
				<el-form-item><!--  高级查询绑定事件    -->
					<el-button type="primary" v-on:click="hightQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--部门数据表格列表列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="180" sortable></el-table-column>
			<el-table-column prop="sn" label="部门编号" width="180" sortable></el-table-column>

			<el-table-column prop="state" label="部门状态" width="180" sortable>
				<template scope="scope">
					<span style="color: #13ce66" v-if="scope.row.state==0">正常</span>
					<span style="color: #409eff" v-else-if="scope.row.state==-1">停用</span>
					<span style="color: red" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页工具条和批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!-- @current-change绑定点击页数事件  pageSize当前页数量 totals总数量  currentPage起始页 -->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" :currentPage="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!-- 添加和编辑界面-->
		<!--
							private String name;
							private String sn;
							private Integer state;
							private Employee manager;
							private Department parent;
		-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
					<!--<el-input v-model="editForm.manager" auto-complete="off"></el-input>-->

					<el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
						<el-option
								v-for="manager in managers"
								:key="manager.id"
								:label="manager.username"
								:value="manager">
							<span style="float: left">{{ manager.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ manager.phone }}</span>
						</el-option>
					</el-select>


				</el-form-item>
				<el-form-item label="上级部门">
					<!--<el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
					<!--deptTree： 级联数据  tree 一级  二级
                        label:'name'  数据中对象的属性name
                        value:'id'    数据中对象的属性id
                        v-model="editForm.parent"  给级联标签绑定值[2,5]
					-->
					<el-cascader v-model="editForm.parent"
							:options="deptTree"
							:props="{ checkStrictly: true,label:'name',value:'id' }"
							clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<!--<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="addForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="addForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {// 双向绑定数据
			return {
				filters: {
                    keyword: ''/*keyword关键字*/
				},
				departments: [],
                managers:[],// 部门经理对应员工的数组
                deptTree:[],// 上级部门集合
                children:'children',// 二级目录
				totals: 0, // mouted方法请求处理
				pageSize: 5,
				currentPage:1,// handleCurrentChange方法绑定事件请求处理的handleCurrentChange
				listLoading: false,
				sels: [],//列表选中列
                title:'',

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				//编辑界面数据  回显到表格的数据
				editForm: {
					name: '',
					sn: '',
                    state: 0,
                    dirPath:'',
                    manager: {},
                    parent: null
				},
			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '正常' : row.state == -1 ? '停用' : '未知';
			},
			// 接收前端点击分页页数接收的
			handleCurrentChange(val) {
				this.currentPage  = val;//接收前台数据向后台发送请求
				this.getDepartments();// 调用方法处理
			},
			/* 高级查询调用时执行的绑定事件方法*/
            hightQuery(){
			    this.currentPage = 1;// 默认第一页展示搜索数据
			    this.getDepartments();// 调用方法与数据处理
			},
			//获取用户列表  接收后台数据和请求到后台数据处理
			getDepartments() {// 在methods函数方法内，调用才会执行
					let para = {
						pageSize: this.pageSize,// 获取当前页条数
						currentPage: this.currentPage,// 获取当前请求的页数
						keyword: this.filters.keyword// keyword传到后台关键字
					};
				this.listLoading = true;// 显示忙态框
				//NProgress.start();
				this.$http.post("/department",para)//跨域post请求后台响应数据
					.then(result=>{// 成功处理
					    console.log("result接收后台数据",result.data);//测试
					    this.departments =result.data.data;// 后台传过来数据对象
					    this.totals = result.data.totalCount;// 后台传递过来总条数
                        console.log("totalCount总条数",result.data.totalCount);
                        this.listLoading = false;// 忙态框  数据加载完成停止忙态继续运行
					}).catch(result=>{// 失败处理
					    alert("操作失败")// 弹框提示
				})
			},
			// 删除数据向后台传递
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 展示忙态框
					//NProgress.start();
                    let para = "/department/"+row.id; // 向后台传数据
					this.$http.delete(para).then(result=>{// 处理成功
                        this.listLoading = false;// 关闭忙态框
                        if(result.data.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            if(this.currentPage>1 && this.totals%this.pageSize==1){// 删除最后一条数据取余
                                this.currentPage=this.currentPage-1
                            }
                            this.getDepartments();
						} else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
						}
					}).catch(result=>{// 弹窗提示
					    alert("系统错误")
					})
					});
			},

			//显示编辑界面忙态框  回显数据给编辑忙态框展示嘛
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
				this.title = "编辑";
				this.getManagers();// 经理数据回显
                this.getDeptTree();// 上级部门
				//this.getManagers();// 回显上级部门数据
				// 数据库中dirPath样子/2/41/90
                let  arr = row.dirPath.split("/");
                // slice起始位置和结束位置之间截取  不包含头尾或者含头不含尾  截取到新的数组中去
                let newarr = arr.slice(1,arr.length-1);
                // 遍数数组
                for (var i = 0;i<newarr.length;i++){
                    // 对数组或者字符串数字截取  比如"1","2","3"截取后123
				newarr[i] = parseInt(newarr[i]);
				}
				// 回显当前员工所在部门和上级部门的关系
                this.editForm.parent=newarr;


			},
			//显示新增界面忙态框  可以给的默认值
			handleAdd: function () {
				this.editFormVisible = true;
				this.editForm = {
                    name: '',
                    sn: '',
                    state: 0,
                    manager: {},
                    parent: null
				};
				this.title = "新增"
				this.getManagers();// 经理回显数据
				this.getDeptTree();// 上级部门
			},
			// 编辑和添加实现
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {// 验证表单数据
					if (valid) {// 判断验证  验证通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;// 显示忙态框
							let para = Object.assign({}, this.editForm);// 回显拷贝数据
							/* 保存上下级部门关系  因为类型问题  直接保存不了  需进一步处理数据处理*/
							if(para.parent != null){//判断不是空时继续执行
                                var arr = para.parent;// 获取上下级路径
                                para.parent = {"id":arr[arr.length-1]};// 截取到路径最后一位就是从第一位开始
								console.log(para.parent);
							}
							this.$http.put("/department",para).then(result=>{// 向后台发送请求数据处理
                                this.editLoading = false;// 关闭忙态框
								if (result.data.success){
                                    this.$message({/*提示框*/
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();//重置表单
                                    this.editFormVisible = false;//关闭编辑模态框
                                    this.getDepartments();// 重新加载数据
								}else {
                                    this.$message({//提示框
                                        message: '提交失败',
                                        type: 'error'
                                    });
								}
							}).catch(result=>{
							    alert("系统错误");

							});
						});



					}
				});
			},
			//新增
/*			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							addDepartment(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getDepartments();
							});
						});
					}
				});
			},*/
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/department",ids).then(res=>{
                        this.listLoading = false;
					    if (res.data.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            // 批量删除最后一页返回上一页显示
                           /* if(this.currentPage>0 && this.totals%this.pageSize==1){// 删除最后一条数据,当前页面没有数据展示则会跳转到有数据页面
                                this.currentPage=this.currentPage-1;
                            }*/
                            if(sessionStorage.getItem('refresh') === 'true') {
                                sessionStorage.removeItem('refresh');
                                location.reload();
                            }

                            this.getDepartments();
						}else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
						}
					}).catch(re=>{
					    alert("系统错误")
					})
				}).catch(() => {

				});
			},
			getManagers(){
                	this.$http.get("/employee",).then(res=>{
                	    this.managers = res.data;
                	    console.log("查询员工",res.data);
					}).catch(res=>{
					    console.log("系统错误")
					})
			},
			/* 上级部门 */
			getDeptTree(){
                this.$http.get("/department/deptTree").then(result=>{
					this.deptTree = result.data;//回显部门数据
				}).catch(result=>{
				alert("系统错误");
				})
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>